package com.kurumi.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.kurumi.mapper.BaseInfoMapper;
import com.kurumi.mapper.MedicalRecordImageMapper;
import com.kurumi.mapper.MedicalRecordMapper;
import com.kurumi.mapper.UploadThirdScanMapper;
import com.kurumi.pojo.MedicalRecord;
import com.kurumi.pojo.MedicalRecordImage;
import com.kurumi.pojo.MedicalRecordTrace;
import com.kurumi.pojo.ScanImage;
import com.kurumi.pojo.upload.UploadThirdScan;
import com.kurumi.pojo.upload.UploadThirdScanFile;
import com.kurumi.query.UploadScanQuery;
import com.kurumi.service.UploadThirdScanService;
import com.kurumi.util.StringUtil;


@Service
public class UploadThirdScanServiceImpl implements UploadThirdScanService {

	@Autowired
	private UploadThirdScanMapper uploadThirdScanMapper;
	
	@Autowired
	private MedicalRecordMapper medicalRecordMapper;
	
	@Autowired
	private MedicalRecordImageMapper medicalRecordImageMapper;
	
	@Autowired
	private BaseInfoMapper baseInfoMapper;
	
	
	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int uploadThirdScan(List<UploadThirdScan> uploadThirdScans){
		// TODO Auto-generated method stub
		
		int count = 0;
		for (UploadThirdScan uploadThirdScan : uploadThirdScans) {
			String[] splits = uploadThirdScan.getUploadFolderName().split("-");
			String visitGuid = null;
			if(splits.length == 2){
				String mrId = splits[0];
				Integer visitNumber = new Integer(splits[1]);
				List<String> visitGuids =medicalRecordMapper.getVisitGuidByMrIdAndVisitNumber( mrId, visitNumber);
				if(visitGuids.size() > 0){
					visitGuid = visitGuids.get(0);
					uploadThirdScan.setVisitGuid(visitGuid);
				}
				if(visitGuid != null){
					List<Map<String,Object>> treatmentTraceTypes = baseInfoMapper.getTraceTypeByCode(MedicalRecordTrace.VISIT_SCAN);
					if(treatmentTraceTypes.isEmpty()){
						throw new RuntimeException(String.format("treatmentTraceTypes %s为空", MedicalRecordTrace.VISIT_SCAN_NAME));
					}
					MedicalRecordTrace scanTrace = new MedicalRecordTrace();
					
					scanTrace.setVisitGuid(visitGuid);
					
					scanTrace.setCreateUserId(uploadThirdScan.getUploadUserCode());
					scanTrace.setCreateUserName(uploadThirdScan.getUploadUserName());
					scanTrace.setTraceTypeCode((String)treatmentTraceTypes.get(0).get("code"));
					scanTrace.setTraceTypeName((String)treatmentTraceTypes.get(0).get("name"));
					count = medicalRecordMapper.insertMedicalRecordTrace(scanTrace);
					if(count != 1){
						throw new RuntimeException(String.format("创建medicalRecordTrace(%s)失败", visitGuid));
					}
				}
				
				
			}
			
			count = uploadThirdScanMapper.insertUploadThirdScan(uploadThirdScan);
			if(count != 1){
				throw new RuntimeException(String.format("创建thirdUploadScan(%s)失败", uploadThirdScan.getUploadFolderName()));
			}
			int index = 0;
			for (ScanImage scanImage : uploadThirdScan.getScanImages()) {
				index++;
				if(uploadThirdScanMapper.getScanImageByFileHash(scanImage.getFileHash()) == null){
					count = uploadThirdScanMapper.insertScanImage(scanImage);
					if(count != 1){
						throw new RuntimeException(String.format("创建scanImage(%s)失败", scanImage.getOriginalFileName()));
					}
				}
				
				UploadThirdScanFile uploadThirdScanFile = new UploadThirdScanFile();
				uploadThirdScanFile.setFileHash(scanImage.getFileHash());
				uploadThirdScanFile.setOriginalFileName(scanImage.getOriginalFileName());
				uploadThirdScanFile.setUploadThirdScanId(uploadThirdScan.getId());
				count = uploadThirdScanMapper.insertUploadThirdScanFile(uploadThirdScanFile);
				if(count != 1){
					throw new RuntimeException(String.format("创建thirdUploadScanFile(%s)失败", uploadThirdScanFile.getOriginalFileName()));
				}
				if(visitGuid != null){
					MedicalRecordImage medicalRecordImage = new MedicalRecordImage();
					medicalRecordImage.setFileHash(scanImage.getFileHash());
					medicalRecordImage.setVisitGuid(visitGuid);
					medicalRecordImage.setCreateUserId(uploadThirdScan.getUploadUserCode());
					medicalRecordImage.setCreateUserName(uploadThirdScan.getUploadUserName());
					medicalRecordImage.setLastUserId(uploadThirdScan.getUploadUserCode());
					medicalRecordImage.setLastUserName(uploadThirdScan.getUploadUserName());
					medicalRecordImage.setSortIndex(index);
					count = medicalRecordImageMapper.insert(medicalRecordImage);
				}
				
				
			}
			
			
		}
		return count;
	}

	@Transactional(readOnly=true)
	@Override
	public List<Map<String, Object>> getUploadThirdScanByQuery(UploadScanQuery query) {
		// TODO Auto-generated method stub
		return uploadThirdScanMapper.getUploadThirdScanByQuery(query);
	}

	@Transactional(readOnly=true)
	@Override
	public int getUploadThirdScanCountByQuery(UploadScanQuery query) {
		// TODO Auto-generated method stub
		return uploadThirdScanMapper.getUploadThirdScanCountByQuery(query);
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int addMedicalRecordRelevance(MedicalRecord medicalRecord, Integer uploadScanId) {
		// TODO Auto-generated method stub
		int count = 0;
		Subject subject=SecurityUtils.getSubject();
		Session session = subject.getSession();
		Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
		String userCode = (String)currentUser.get("user_code");
		String userName = (String)currentUser.get("user_name");
		medicalRecord.setVisitGuid(StringUtil.getId());
		medicalRecord.setVersion(1);
		count = medicalRecordMapper.insert(medicalRecord);
		if(count != 1){
			throw new RuntimeException(String.format("创建medicalRecord(%s)失败", medicalRecord.getOnlyId()));
		}
		List<Map<String,Object>> treatmentTraceTypes = baseInfoMapper.getTraceTypeByCode(MedicalRecordTrace.VISIT_INIT);
		
		if(treatmentTraceTypes.isEmpty()){
			throw new RuntimeException(String.format("treatmentTraceTypes %s为空", MedicalRecordTrace.VISIT_INIT_NAME));
		}
		
		MedicalRecordTrace medicalRecordTrace = new MedicalRecordTrace();
		
		medicalRecordTrace.setVisitGuid(medicalRecord.getVisitGuid());
		
		medicalRecordTrace.setCreateUserId(userCode);
		medicalRecordTrace.setCreateUserName(userName);
		medicalRecordTrace.setTraceTypeCode((String)treatmentTraceTypes.get(0).get("code"));
		medicalRecordTrace.setTraceTypeName((String)treatmentTraceTypes.get(0).get("name"));
		count = medicalRecordMapper.insertMedicalRecordTrace(medicalRecordTrace);
		if(count != 1){
			throw new RuntimeException(String.format("创建medicalRecordTrace(%s)失败", medicalRecord.getOnlyId()));
		}
		
		
		List<String> fileHashs = uploadThirdScanMapper.getFileHashByUploadScanId(uploadScanId);
		int index = 0;
		for (String fileHash : fileHashs) {
			index ++;
			MedicalRecordImage medicalRecordImage = new MedicalRecordImage();
			medicalRecordImage.setFileHash(fileHash);
			medicalRecordImage.setVisitGuid(medicalRecord.getVisitGuid());
			medicalRecordImage.setCreateUserId(userCode);
			medicalRecordImage.setCreateUserName(userName);
			medicalRecordImage.setLastUserId(userCode);
			medicalRecordImage.setLastUserName(userName);
			medicalRecordImage.setSortIndex(index);
			count = medicalRecordImageMapper.insert(medicalRecordImage);
			if(count != 1){
				throw new RuntimeException(String.format("新建medicalRecordImage(%s)失败", fileHash));
			}
		}
		count = uploadThirdScanMapper.updateUploadThirdScanOfVisitGuidByPrimaryKey(uploadScanId,medicalRecord.getVisitGuid());
		if(count != 1){
			throw new RuntimeException(String.format("修改UploadThirdScan(%s)失败", medicalRecord.getOnlyId()));
		}
		
		treatmentTraceTypes = baseInfoMapper.getTraceTypeByCode(MedicalRecordTrace.VISIT_PIGEONHOLE);
		if(treatmentTraceTypes.isEmpty()){
			throw new RuntimeException(String.format("treatmentTraceTypes %s为空", MedicalRecordTrace.VISIT_PIGEONHOLE_NAME));
		}
		MedicalRecordTrace pigeonholeTrace = new MedicalRecordTrace();
		
		pigeonholeTrace.setVisitGuid(medicalRecord.getVisitGuid());
		
		pigeonholeTrace.setCreateUserId(userCode);
		pigeonholeTrace.setCreateUserName(userName);
		pigeonholeTrace.setTraceTypeCode((String)treatmentTraceTypes.get(0).get("code"));
		pigeonholeTrace.setTraceTypeName((String)treatmentTraceTypes.get(0).get("name"));
		count = medicalRecordMapper.insertMedicalRecordTrace(pigeonholeTrace);
		
		
		treatmentTraceTypes = baseInfoMapper.getTraceTypeByCode(MedicalRecordTrace.VISIT_SCAN);
		if(treatmentTraceTypes.isEmpty()){
			throw new RuntimeException(String.format("treatmentTraceTypes %s为空", MedicalRecordTrace.VISIT_SCAN_NAME));
		}
		MedicalRecordTrace scanTrace = new MedicalRecordTrace();
		
		scanTrace.setVisitGuid(medicalRecord.getVisitGuid());
		
		scanTrace.setCreateUserId(userCode);
		scanTrace.setCreateUserName(userName);
		scanTrace.setTraceTypeCode((String)treatmentTraceTypes.get(0).get("code"));
		scanTrace.setTraceTypeName((String)treatmentTraceTypes.get(0).get("name"));
		count = medicalRecordMapper.insertMedicalRecordTrace(scanTrace);
		if(count != 1){
			throw new RuntimeException(String.format("创建medicalRecordTrace(%s)失败", medicalRecord.getVisitGuid()));
		}
		return count;
	}

	@Transactional(propagation=Propagation.REQUIRED)
	@Override
	public int medicalRecordRelevance(String mrId, Integer visitNumber, Integer uploadScanId) {
		// TODO Auto-generated method stub
		int count = 0;
		Subject subject=SecurityUtils.getSubject();
		Session session = subject.getSession();
		Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
		String userCode = (String)currentUser.get("user_code");
		String userName = (String)currentUser.get("user_name");
		List<String> fileHashs = uploadThirdScanMapper.getFileHashByUploadScanId(uploadScanId);
		List<String> visitGuids =medicalRecordMapper.getVisitGuidByMrIdAndVisitNumber( mrId, visitNumber);
		if(visitGuids.isEmpty()){
			throw new RuntimeException(String.format("查询visitGuid(%s)为空", mrId));
		}
		String visitGuid = visitGuids.get(0);
		int index = 0;
		for (String fileHash : fileHashs) {
			index ++;
			MedicalRecordImage medicalRecordImage = new MedicalRecordImage();
			medicalRecordImage.setFileHash(fileHash);
			medicalRecordImage.setVisitGuid(visitGuid);
			medicalRecordImage.setCreateUserId(userCode);
			medicalRecordImage.setCreateUserName(userName);
			medicalRecordImage.setLastUserId(userCode);
			medicalRecordImage.setLastUserName(userName);
			medicalRecordImage.setSortIndex(index);
			count = medicalRecordImageMapper.insert(medicalRecordImage);
			if(count != 1){
				throw new RuntimeException(String.format("新建medicalRecordImage(%s)失败", fileHash));
			}
		}
		count = uploadThirdScanMapper.updateUploadThirdScanOfVisitGuidByPrimaryKey(uploadScanId,visitGuid);
		if(count != 1){
			throw new RuntimeException(String.format("修改UploadThirdScan(%s)失败", mrId));
		}
		
		List<Map<String,Object>>  treatmentTraceTypes = baseInfoMapper.getTraceTypeByCode(MedicalRecordTrace.VISIT_SCAN);
		if(treatmentTraceTypes.isEmpty()){
			throw new RuntimeException(String.format("treatmentTraceTypes %s为空", MedicalRecordTrace.VISIT_SCAN_NAME));
		}
		MedicalRecordTrace scanTrace = new MedicalRecordTrace();
		
		scanTrace.setVisitGuid(visitGuid);
		
		scanTrace.setCreateUserId(userCode);
		scanTrace.setCreateUserName(userName);
		scanTrace.setTraceTypeCode((String)treatmentTraceTypes.get(0).get("code"));
		scanTrace.setTraceTypeName((String)treatmentTraceTypes.get(0).get("name"));
		count = medicalRecordMapper.insertMedicalRecordTrace(scanTrace);
		if(count != 1){
			throw new RuntimeException(String.format("创建medicalRecordTrace(%s)失败", visitGuid));
		}
		return count;
	}

}
